package com.demo.controller;

import com.demo.core.exception.ParameterException;
import com.demo.utils.VerifyUtil;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.OutputStream;

@RestController
@RequestMapping("verify")
public class VerifyController {

    // 生成验证码
    @Operation(summary = "验证")
    @PostMapping("/getCode")
    public void getCode(HttpServletResponse response, HttpServletRequest request) throws Exception, ParameterException {
        if (request == null || response == null) {
            throw new ParameterException("request或response为null");
        } else {
            // 获取当前会话
            HttpSession httpSession = request.getSession();
            // 会话ID（每个用户——唯一对话）
            String id = httpSession.getId();

            Object[] obj = VerifyUtil.newBuilder()
                    .setSize(4)
                    .setLines(10)
                    .setWidth(130)
                    .setHeight(40)
                    .setFontSize(30)
                    .setTilt(true)
                    .setBackgroundColor(Color.LIGHT_GRAY)
                    .build()
                    .createImage();

            // 将验证码存入Session
            httpSession.setAttribute("verifyCode" + id, obj[0]);
            // 打印验证码
            System.out.println(obj[0]);
            // 将图片输出给浏览器
            BufferedImage image = (BufferedImage) obj[1];
            // 告诉客户端响应应该包含一个PNG格式的图片
            response.setContentType("image/png");
            // 获取输出流
            OutputStream os = response.getOutputStream();
            // 将验证图片写入到HTTP响应的输出流中
            ImageIO.write(image, "png", os);
        }

    }


    // 验证验证码输入是否正确
    @GetMapping("/checkcode")
    public String checkCode(String code, HttpServletRequest request) throws ParameterException {

        if (request == null) {
            throw new ParameterException("request为null");
        } else if (code.length() != 6) {
            throw new ParameterException("code值非法");
        } else {
            HttpSession session = request.getSession();
            String id = session.getId();
            // 将session中的取出对应session id生成的验证码
            String serverCode = (String) session.getAttribute("verifyCode" + id);
            // 校验验证码
            if (serverCode == null || code == null || !serverCode.equals(code)) {
                return "验证码错误!";
            }
            return "验证码正确!";
        }

    }

}
